package com.itcc.dao.impl;

import com.itcc.dao.BrowseDao;
import com.itcc.dao.ProductDao;
import com.itcc.entity.Browse;
import com.itcc.entity.Product;
import com.itcc.utils.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class BrowseDaoImpl implements BrowseDao {
    @Override
    public void insertRecord(String uid, String pid) throws SQLException {
        ProductDao productDao=new ProductDaoImpl();
        Product product = productDao.selectProductByPid(pid);

        QueryRunner queryRunner=new QueryRunner(C3P0Utils.getDataSource());

        String sql="insert into browse (u_id,p_id,r_time,p_image,p_name,p_price) values (?,?,?,?,?,?);";

        // 获取当前时间
        Date currentDate = new Date();

        // 格式化当前时间为年月日
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = dateFormat.format(currentDate);

        // 将格式化后的时间插入到数据库
        queryRunner.update(sql, Integer.parseInt(uid), Integer.parseInt(pid), formattedDate,product.getPimage(),product.getPname(),product.getPprice());
    }

    @Override
    public List<Browse> findBrowsesByUid(String uid) throws SQLException {

        QueryRunner queryRunner=new QueryRunner(C3P0Utils.getDataSource());

        String sql="select r_id as rid,u_id as uid,p_id as pid,r_time as rtime,p_image as pimage,p_name as pname,p_price as pprice from browse where u_id=? ORDER BY rtime DESC;";

        List<Browse> browseList = queryRunner.query(sql, new BeanListHandler<>(Browse.class), uid);

        return browseList;
    }
}
